import Vue from "vue"
import Router from "vue-router"
import Login from "@/views/login/login"
// 因为动态添加路由失效，暂时一次性添加所有路由
import registerRoute from "./modules";

Vue.use(Router)

const routes = [
    {
        // 登录
        path: "/",
        props: {
            identity: "user", // 默认会员登录
        },
        component: Login,
    },
]

// 初始化路由结构和模式history
const router = new Router({
    mode: "history",
    base: process.env.VUE_APP_BASE_URL,
    routes,
    scrollBehavior(to, from, savedPosition) {
        if (savedPosition) {
            return savedPosition;
        } else {
            return {
                x: 0,
                y: 0,
            };
        }
    },
});

// 不需要鉴权的页面
const whiteList = [
    "Login"
];

// 登陆认证鉴权页面控制
router.beforeEach((to, from, next) => {
    const token = sessionStorage.getItem("token");

    if (whiteList.includes(to.name)) {
        // 在白名单
        next();
    } else if (token) {
        // 有进行登录
        next();
    } else {
        // 默认跳转
        next({
            name: "Login",
            replace: true,
        });
    }
});

export default router;

// 手动加载路由
router.addRoutes([
    ...registerRoute.getUserRoute(),
]);
